<?php defined('SYSPATH') or die('No direct access allowed.');

class Model_Api_V2_Line
{
    public static $_typeid = 1;

    public static function search($params)
    {
        $status       = true;
        $dest_pinyin  = $params['destpy'];
        $day_id       = intval($params['dayid']);
        $price_id     = intval($params['priceid']);
        $sort_type    = intval($params['sorttype']);
        $startcity_id = intval($params['startcityid']);
        $attr_id      = $params['attrid'];
        $page         = intval($params['page']);
        $page         = $page ? $page : 1;
        $pagesize     = intval($params['pagesize']);
        $pagesize     = $pagesize ? $pagesize : 5;
        $keyword      = St_String::filter_mark(Common::remove_xss($params['keyword']));


        $value_arr = array();
        $where     = " WHERE a.ishidden=0 ";
        //按目的地搜索
        if ($dest_pinyin && $dest_pinyin != 'all') {
            $destId = DB::select('id')->from('destinations')->where('pinyin', '=', $dest_pinyin)->execute()->get('id');
            //如果找不到则跳转404页面
            if (!empty($destId)) {
                $where .= " AND FIND_IN_SET('$destId',a.kindlist) ";
            }

        }
        //天数
        if ($day_id) {
            $days = DB::select('word')->from('line_day')->where('id', '=', $day_id)->execute()->get('word', 0);
            if (!empty($days)) {
                if (self::is_last_day($days)) {
                    $where .= " AND a.lineday>='$days'";
                } else {
                    $where .= " AND a.lineday='$days'";
                }
            }


        }
        //价格区间
        if ($price_id) {
            $priceArr = DB::select()->from('line_pricelist')->where('id', '=', $price_id)->execute()->current();
            if (!empty($priceArr)) {
                $where .= " AND a.price BETWEEN {$priceArr['lowerprice']} AND {$priceArr['highprice']} ";
            }

        }
        //排序
        $orderBy = "";
        if (!empty($sort_type)) {
            if ($sort_type == 1)//价格升序
            {
                $orderBy = "  a.price ASC,";
            } else if ($sort_type == 2) //价格降序
            {
                $orderBy = "  a.price DESC,";
            } else if ($sort_type == 3) //销量降序
            {
                $orderBy = " sellnum desc,";
            } else if ($sort_type == 4)//推荐
            {
                $orderBy = " a.recommendnum DESC,";
            }
            /*  else if($sortType==5) //满意度
              {
                  $orderBy = " a.shownum desc,";
              }*/
        }

        //出发城市
        if (!empty($startcity_id)) {
            $city = self::start_city($startcity_id);
            if (!empty($city)) {
                $where .= " AND a.startcity='$startcity_id' ";
            }

        }
        //按属性
        if (!empty($attr_id)) {

            $where .= self::get_attr_where($attr_id);
        }
        //按关键词
        if (!empty($keyword)) {

            if (preg_match('`([a-zA-Z])(\d{3,8})`', $keyword, $preg)) {
                $id               = ltrim($preg[2], '0');
                $where            .= " AND a.id=:id";
                $value_arr[':id'] = $id;
            } else if (is_numeric($keyword)) {
                $result           = St_Product::product_series($keyword, '', true);
                $where            .= " AND a.id=:id";
                $value_arr[':id'] = $result['id'];

            } else {
                $where                 .= " AND a.title like :keyword ";
                $value_arr[':keyword'] = '%' . $keyword . '%';

            }
        }

        $offset = (intval($page) - 1) * $pagesize;

        $orderBy = empty($orderBy) ? " IFNULL(b.displayorder,9999) ASC, " : $orderBy;

        //查询真实购买量
        $sell_where = " LEFT JOIN (SELECT COUNT(*) as s_num,productautoid FROM `sline_member_order` WHERE typeid=1 GROUP BY productautoid) AS s ON s.productautoid=a.id";
        $files      = ",(IFNULL(a.bookcount,0)+IFNULL(s.s_num,0)) AS sellnum";

        //如果选择了目的地
        if (!empty($destId)) {
            $sql = "SELECT a.*{$files} FROM `sline_line` a ";
            $sql .= "LEFT JOIN `sline_kindorderlist` b ";
            $sql .= "ON (a.id=b.aid AND b.typeid=1 AND a.webid=b.webid AND b.classid='$destId')";
            $sql .= $sell_where;
            $sql .= $where;
            $sql .= "ORDER BY {$orderBy} IFNULL(b.displayorder,9999) ASC, a.modtime DESC,a.addtime DESC ";
        } else {
            $sql = "SELECT a.*{$files} FROM `sline_line` a ";
            $sql .= "LEFT JOIN `sline_allorderlist` b ";
            $sql .= "ON (a.id=b.aid AND b.typeid=1 AND a.webid=b.webid)";
            $sql .= $sell_where;
            $sql .= $where;
            $sql .= "ORDER BY {$orderBy} IFNULL(b.displayorder,9999) ASC, a.modtime DESC,a.addtime DESC ";
        }

        //计算总数
        $totalSql = "SELECT count(*) as dd " . strchr($sql, " FROM");
        $totalSql = str_replace(strchr($totalSql, "ORDER BY"), '', $totalSql);//去掉order by


        $totalN   = DB::query(1, $totalSql)->parameters($value_arr)->execute()->as_array();
        $totalNum = $totalN[0]['dd'] ? $totalN[0]['dd'] : 0;

        //数据量大时的优化方法,数据量小时不推荐使用此方法
        //$idWhere = "SELECT id FROM `sline_line` ORDER BY id limit $offset, 1";
        //$sql = str_replace("WHERE","WHERE a.id>($idWhere) AND",$sql);
        //$sql.= "LIMIT {$pagesize}";

        //检测页面数量是否超限
        $total_page = (int)ceil($totalNum / $pagesize);
        if (($total_page > 0 and intval($page) > $total_page) or ($total_page == 0 and $page > 1)) {
            $status = false;
        }


        $sql .= "LIMIT {$offset},{$pagesize}";

        $arr = DB::query(1, $sql)->parameters($value_arr)->execute()->as_array();
        foreach ($arr as &$v) {
            $v['price']      = Model_Line::get_minprice($v['id'], $v);
            $v['attrlist']   = Model_Line::line_attr($v['attrid']);
            $v['startcity']  = Model_Startplace::start_city($v['startcity']);
            $v['commentnum'] = Model_Comment::get_comment_num($v['id'], 1); //评论次数
            $v['sellnum']    = Model_Member_Order::get_sell_num($v['id'], 1) + intval($v['bookcount']); //销售数量
            //$v['url'] = Common::get_web_url($v['webid']) . "/lines/show_{$v['aid']}.html";
            $v['litpic']    = Model_Api_V2_System::uniapp_img($v['litpic'], 750, 400);
            $v['iconlist']  = Model_Api_V2_System::get_ico_list($v['iconlist']);
            $v['startdate'] = Model_Line::get_startdate($v);
            $v['score']     = St_Functions::get_satisfy(self::$_typeid, $v['id'], $v['satisfyscore']);
        }
        $out = array(
            'total' => $totalNum,
            'list' => $arr,
            'status' => $status
        );
        return $out;

    }


    public static function detail($params)
    {
        if ($params['id']) {
            $id     = $params['id'];
            $userid = $params['userid'];
            $info   = DB::select()->from('line')->where('id', '=', $id)->execute()->current();
            if (empty($info)) {
                return array();
            }
            //seo
            $seo_info = Product::seo($info);

            $info['seo_info'] = $seo_info;
            //产品图片
            $piclist = Product::pic_list($info['piclist']);
            $p       = array();
            foreach ($piclist as &$pic) {
                $pi = Model_Api_V2_System::uniapp_img($pic[0], 750, 400);
                array_push($p, $pi);
            }
            if (empty($p)) {
                $p[0] = Model_Api_V2_System::uniapp_img('');
            }
            $info['piclist'] = $p;
            //属性列表
            $info['attrlist'] = Model_Line::line_attr($info['attrid']);

            $info['price'] = Model_Line::get_minprice($info['id'], array('info' => $info));

            //会员折扣
            $cfg_line_minprice_rule     = $GLOBALS['cfg_line_minprice_rule'];
            $cfg_line_minprice_rule     = empty($cfg_line_minprice_rule) ? 2 : $cfg_line_minprice_rule;
            $info['discount_min_price'] = Model_Api_V2_Discount::get_discount($userid, self::$_typeid, $id, $info['price'], $cfg_line_minprice_rule);
            //出发城市
            $info['startcity'] = Model_Startplace::start_city($info['startcity']);
            //点评数
            $info['commentnum'] = Model_Comment::get_comment_num($info['id'], 1);
            //销售数量
            $info['sellnum'] = Model_Member_Order::get_sell_num($info['id'], 1) + intval($info['bookcount']);
            //产品编号
            $info['series'] = St_Product::product_series($info['id'], 1);
            //产品图标
            $info['iconlist'] = Product::get_ico_list($info['iconlist']);
            //行程附件
            $info['linedoc'] = unserialize($info['linedoc']);

            $info['linedoc_path'] = empty($info['linedoc']['path']) ? '' : Model_Api_V2_System::reorganized_resource_url($info['linedoc']['path'][0]);
            //满意度
            $info['score'] = St_Functions::get_satisfy(self::$_typeid, $info['id'], $info['satisfyscore']);

            $info['litpic'] = Model_Api_V2_System::uniapp_img($info['litpic']);

            $info['basehost'] = $GLOBALS['cfg_basehost'];

            $info['jieshao'] = Model_Api_V2_Xcx::filter_content($info['jieshao']);

            // 处理视频
            if ($info['product_video']) {
                $product_video         = explode('|', $info['product_video']);
                $info['product_video'] = isset($product_video[0]) ? Model_Api_V2_System::reorganized_resource_url($product_video[0]) : '';
            }

            //扩展字段信息
            $extend_info         = ORM::factory('line_extend_field')
                ->where("productid=" . $info['id'])
                ->find()
                ->as_array();
            $info['extend_info'] = $extend_info;

            //套餐信息
            $info['suit_info'] = self::suit($info['id']);

            //线路详情内容
            $params              = array(
                'typeid' => '1',
                'productinfo' => $info,
                'onlyrealfield' => 1,
                'pc' => 0
            );
            $info['detail_list'] = self::get_detail_content($params);

            //分销赚取的金额
            if (St_Functions::is_normal_app_install('mobiledistribution')) {
                if (!empty($userid)) {
                    $fxgroupid       = DB::select('fxgroupid')->from('fenxiao')->where("memberid", '=', $userid)->execute()->current();
                    $commission_type = Model_Fenxiao_Config::get_val('cfg_fenxiao_commission_type_' . $params['typeid'], $fxgroupid['fxgroupid']);
                    if ($commission_type == 1) {
                        $commission_rate = Model_Fenxiao::get_commission_rate($params['typeid'], $info['id'], $fxgroupid['fxgroupid']);
                        $v['commission'] = $commission_rate[0] * 100;
                        $v['commission'] = empty($v['commission']) ? 0 : $v['commission'];
                        $v['commission'] .= '%';
                        $v['profit']     = $info['price'] * $commission_rate[0];
                    } else if ($commission_type == 2) {
                        $commission_rate = Model_Fenxiao::get_commission_rate_platform($params['typeid'], $info['id'], $fxgroupid['fxgroupid']);
                        $v['commission'] = $commission_rate[0] * 100;
                        $v['commission'] = empty($v['commission']) ? 0 : $v['commission'];
                        $v['commission'] .= '%';
                        $temp_order      = array('typeid' => $params['typeid'], 'productautoid' => $info['id'], 'totalprice' => $info['price'], 'dingnum' => 1, 'channel_id' => 1);
                        $platform_price  = Model_Member_Order_Compute::caculate_platform_commission($temp_order);
                        $platform_price  = $platform_price == 0 ? $info['price'] : $platform_price;
                        $v['profit']     = $platform_price * $commission_rate[0];
                    } else {
                        $commission_cash = Model_Fenxiao::get_commission_cash_line($params['typeid'], $info['id'], $fxgroupid['fxgroupid']);
                        $v['commission'] = $commission_cash[0]['adult'];
                        $v['commission'] = empty($v['commission']) ? 0 : $v['commission'];
                        $v['profit']     = $v['commission'];
                    }
                    $info['profit'] = Currency_Tool::price($v['profit']);
                }
            }

            $info['near_price_days'] = self::_get_near_price_days($info);

            // 积分抵现配置
            $jifenprice_info          = Model_Jifen_Price::get_used_jifentprice($info['jifentprice_id'], 1);
            $info['jifentprice_info'] = $jifenprice_info;
            // 预定送积分
            $jifenbook_info         = Model_Jifen::get_used_jifenbook($info['jifenbook_id'], 1);
            $info['jifenbook_info'] = $jifenbook_info;
            //积分评论
            $jifencomment_info         = Model_Jifen::get_used_jifencomment(1);
            $info['jifencomment_info'] = $jifencomment_info;

            return $info;
        } else {
            return array();
        }

    }

    /**
     * 获取指定指定字段的的线路信息
     * @param $id
     * @param $field
     * @return mixed|null
     */
    public static function get_field_detail($id, $field = '')
    {
        $field = $field ? DB::expr($field) : '*';
        return DB::select($field)
            ->from('line')
            ->where('id', '=', $id)
            ->execute()
            ->current();
    }

    /**
     * @function 栏目信息
     * @return mixed
     */
    public static function channel()
    {
        $row = DB::select()
            ->from('nav')
            ->where('typeid', '=', 1)
            ->and_where('issystem', '=', 1)
            ->execute()
            ->current();
        return $row;
    }

    /**
     * @param $lineday
     * @return int
     */
    public static function is_last_day($lineday)
    {
        $row = DB::select()
            ->from('line_day')
            ->where('word', '>', $lineday)
            ->limit(1)
            ->execute()
            ->current();
        return $row['word'] > 0 ? 0 : 1;
    }

    /**
     * @function 出发地
     * @param $city_id
     * @return mixed
     */
    public static function start_city($city_id)
    {
        if (empty($city_id) || preg_match('/[\x{4e00}-\x{9fa5}]+/u', $city_id)) {
            return $city_id;
        }
        $city = DB::select('cityname')
            ->from('startplace')
            ->where('id', '=', $city_id)
            ->execute()
            ->current();
        return $city['cityname'];
    }

    /*
     * 属性生成where条件,用于多条件属性搜索.
     * */
    public static function get_attr_where($attrid)
    {
        $arr = Common::remove_arr_empty(explode('_', $attrid));
        foreach ($arr as $value) {
            $value = intval($value);
            if ($value != 0) {
                $str .= " and FIND_IN_SET($value,a.attrid) ";
            }
        }
        return $str;
    }

    /**
     * 获取线路套餐列表
     * @param $productid
     * @param $card_suit_id
     * @return Array
     */
    public static function suit($productid, $card_suit_id=false)
    {
        $pay_name = array(
            '1' => '全款支付',
            '2' => '定金支付',
            '3' => '二次确认'
        );
        $model = DB::select()->from('line_suit')
            ->where('lineid','=',$productid);
        if($card_suit_id){
            $model->and_where('id','in',explode(',',$card_suit_id));
        }
        $suit = $model->order_by('displayorder','ASC')
            ->execute()
            ->as_array();
        foreach ($suit as &$r)
        {
            $beforBook = array(
                'suitid' => $r['id'],
                'info' => $r
            );
            $r['price'] = Model_Line::get_minprice($r['lineid'], $beforBook);
            $r['description'] = Model_Api_V2_Xcx::filter_content($r['description']);
            $r['title'] = $r['suitname'];
            $r['paytype_name'] = $pay_name[$r['paytype']];
        }
        return $suit;
    }

    /**
     * @function 获取线路详细行程内容
     * @param $params
     * @return array
     */
    private static function get_detail_content($params)
    {

        $default = array(
            'typeid' => '1',
            'productinfo' => 0,
            'onlyrealfield' => 1,
            'pc' => 0

        );
        $params  = array_merge($default, $params);
        extract($params);
        $arr = DB::select()->from('line_content')
            ->where('webid', '=', 0)
            ->and_where('isopen', '=', 1)
            ->order_by('displayorder', 'ASC')
            ->execute()
            ->as_array();


        //扩展表数据
        $productid = $productinfo['id'];//产品id
        $ar        = DB::select()->from('line_extend_field')->where('productid', '=', $productid)->execute()->as_array();

        $list = array();
        foreach ($arr as $v) {
            if ($v['columnname'] == 'tupian' || $v['columnname'] == 'linedoc') {
                continue;
            }
            if ($v['isrealfield'] == 1) {
                $content = !empty($productinfo[$v['columnname']]) ? $productinfo[$v['columnname']] : $ar[0][$v['columnname']];
                $content = $content ? $content : '';
                if (empty($content)) {
                    continue;
                }
            }
            $a = array();


            $a['columnname']  = $v['columnname'];
            $a['chinesename'] = $v['chinesename'];
            if ($typeid == 1 && $v['columnname'] == 'jieshao' && $productinfo['isstyle'] == 2) {
                $lineContent = DB::query(1, "SELECT * FROM sline_line_jieshao where lineid =" . $productinfo['id'] . " and `day`=1 and title!='' and title is not null")->execute()->current();

                if (!$lineContent) {
                    continue;
                } else {
                    $detail = Model_Line_Jieshao::detail($productinfo['id'], $productinfo['lineday']);

                    foreach ($detail as &$d) {
                        $d['jieshao'] = Model_Api_V2_Xcx::filter_content($d['jieshao']);
                        if (St_Functions::is_system_app_install(5)) {
                            $line_spot = Taglib_Line::line_spot(array('day' => $d['day'], 'productid' => $d['lineid'], 'row' => '4',));
                            foreach ($line_spot as &$s) {
                                $s['litpic'] = Model_Api_V2_System::reorganized_resource_url($s['litpic']);
                            }
                            $d['line_spot'] = $line_spot;
                        }
                    }
                    $a['content']  = $detail;
                    $a['is_array'] = 1;
                }
            } else if ($v['columnname'] == 'jieshao' && $productinfo['isstyle'] == 1) {
                $content = $productinfo['jieshao'];
                if (empty($content)) {
                    continue;
                }
                $a['content']  = Model_Api_V2_Xcx::filter_content($content);
                $a['is_array'] = 0;

            } else {
                $a['content'] = Model_Api_V2_Xcx::filter_content($content);
            }

            //$a['xcx_content'] = Model_Api_V2_System::filter_content($content); //针对小程序去除样式
            //$a['content'] = Model_Api_V2_System::filter_content($content);
            $list[] = $a;

        }
        return $list;
    }

    /**
     * @function 获取最近可预订的日期
     * @param $line_info
     * @param int $num
     */
    public static function _get_near_price_days($line_info, $num = 3)
    {
        $start_day_time = time();
        if (!empty($line_info['linebefore']) && $line_info['islinebefore'] > 0) {
            $start_day_time = strtotime('+ ' . $line_info['linebefore'] . ' days');
        }
        $start_day_time = strtotime(date('Y-m-d 0:0:0', $start_day_time));

        $price_day_list = DB::query(Database::SELECT, "select * from sline_line_suit_price where day>={$start_day_time} and lineid='{$line_info['id']}' and (number>0 or number=-1) group by day order by day asc limit {$num}")->execute()->as_array();

        $cfg_line_minprice_rule = $GLOBALS['cfg_line_minprice_rule'];

        $min_price_field = 'adultprice';

        $people_group    = Model_Sysconfig::get_people_group(null, 1);
        $min_price_field = $people_group[$cfg_line_minprice_rule]['price_field'] ? $people_group[$cfg_line_minprice_rule]['price_field'] : $min_price_field;

        foreach ($price_day_list as $key => $price_day) {
            $where         = " lineid='{$line_info['id']}' and day='{$price_day['day']}' and (number!=0 or number=-1) ";
            $min_price_day = DB::query(Database::SELECT, "select * from sline_line_suit_price where  {$where} and {$min_price_field}>0 order by {$min_price_field} asc limit 1")->execute()->current();
            if (!empty($min_price_day)) {
                $min_price_day['min_price'] = $min_price_day[$min_price_field];
            }

            $min_day   = array();
            $min_price = 0;
            if (empty($min_price_day)) {
                foreach ($people_group as $people) {
                    $cur_day = DB::query(Database::SELECT, "select * from sline_line_suit_price where  {$where} and {$people['price_field']}>0 order by {$people['price_field']} asc limit 1")->execute()->current();
                    if (!empty($cur_day) && ($cur_day[$people['price_field']] < $min_price || $min_price == 0)) {
                        $min_price_day              = $cur_day;
                        $min_price_day['min_price'] = $min_price_day[$people['price_field']];
                        $min_price                  = $min_price_day[$people['price_field']];
                    }
                }
            }

            $min_price_day['min_price'] = Currency_Tool::price($min_price_day['min_price']);
            $min_price_day['day']       = date('Y-m-d', $min_price_day['day']);
            $price_day_list[$key]       = $min_price_day;
        }
        return $price_day_list;
    }

    /**
     * 获取价格日历报价
     * @param $suitid
     * @param $productid
     * @return array
     */
    public static function get_price_calendar_json($suitid, $productid)
    {
        $info                = Model_Api_V2_Line::get_field_detail($productid, 'islinebefore,linebefore');
        $ext                 = array();
        $ext['islinebefore'] = $info['islinebefore'];
        $ext['linebefore']   = $info['linebefore'];

        $price_arr              = Model_Line::get_month_price_new($suitid);
        $cfg_line_minprice_rule = $GLOBALS['cfg_line_minprice_rule'];
        $data                   = array();
        foreach ($price_arr as $k => &$v) {
            switch ($cfg_line_minprice_rule) {
                case 1:
                    $price = $v['child_price'];
                    break;
                case 2:
                    $price = $v['price'];
                    break;
                case 3:
                    $price = $v['old_price'];
                    break;
                default:
                    $price = $v['people' . $cfg_line_minprice_rule . '_price'];
                    break;
            }
            $price  = empty($price) ? min(array_filter(array(floatval($v['child_price']), floatval($v['price']), floatval($v['old_price']), floatval($v['people4_price']), floatval($v['people5_price']), floatval($v['people6_price'])))) : $price;
            $before = !($ext['islinebefore'] > 0 && $ext['linebefore'] > 0) ? strtotime(date('Ymd') . " 0:0:0") : strtotime("+{$ext['linebefore']} days", strtotime(date('Ymd') . " 0:0:0"));
            if ($k < $before) {
                continue;
            }

            $data[date('Ymd', $k)] = array(
                'date' => date('m-d', $k),
                'fulldate' => date('Y-m-d', $k),
                'times' => date('Y-m-d', $k),
                'day' => intval(date('d', $k)),
                'price' => $price,
                'child_price' => $v['child_price'],
                'old_price' => $v['old_price'],
                'number' => $v['number'],
                'adult_price' => $v['price'],
                'adultprice' => $v['price'],
                'people4_price' => $v['people4_price'],
                'people5_price' => $v['people5_price'],
                'people6_price' => $v['people6_price'],
                'roombalance' => $v['roombalance']
            );
        }
        return $data;
    }

    /**
     * 检查预定参数
     * @param $request_data
     * @return array
     * @throws Exception
     */
    public static function check_order_params($request_data, $member_id)
    {
        $product_id = intval($request_data->productautoid);
        $suit_id    = intval($request_data->suitid);

        //产品信息
        $info = self::get_field_detail($product_id);

        //下架状态判断
        if ($info['status'] != 3) {
            throw new Exception('当前产品已下架，不可预订');
        }

        // 套餐信息
        $suit_info = Model_Line_Suit::suit_info($suit_id);

        //成人数量
        $dingnum = $request_data->dingnum ?: 0;
        //小孩数量
        $childnum = $request_data->childnum ?: 0;
        //老人数量
        $oldnum = $request_data->oldnum ?: 0;
        //人群4
        $people4_num = $request_data->people4num ?: 0;
        //人群5
        $people5_num = $request_data->people5num ?: 0;
        //人群6
        $people6_num = $request_data->people6num ?: 0;

        $ding_num = St_Math::add(array($dingnum, $childnum, $oldnum, $people4_num, $people5_num, $people6_num), 0);

        // 检查秒杀活动限制
        $seckill_id = $request_data->seckill_id ?: 0;
        if ($seckill_id > 0) {
            if (St_Functions::is_normal_app_install('seckill')) {
                $status = Model_Seckill::get_seckill_num($seckill_id, $member_id);
                if (!$status) {
                    throw new Exception('已超出秒杀活动限制次数');
                }
            }
        }

        // 检查拼团或凑团限制
        $together_id = $request_data->together_id ?: 0;
        $join_id     = $request_data->join_id ?: 0;
        if ($together_id > 0 || $join_id > 0) {
            if (St_Functions::is_normal_app_install('together')) {
                $together_params      = array('join_id' => $join_id, 'ding_num' => $ding_num);
                $check_order_together = Model_Api_V2_Together::check_order_together($together_id, $member_id, $together_params);
                if (!$check_order_together['status']) {
                    throw new Exception($check_order_together['msg']);
                }
                $together_info  = $check_order_together['data'];
                $together_price = $together_info['price'];
            }
        }

        //出发日期
        $use_date = $request_data->usedate;
        if (strtotime($use_date) < strtotime(date('Y-m-d', time()))) {
            throw new Exception('出发日期不正确');
        }

        // 判断是否有套餐报价
        $price_arr = DB::select()
            ->from('line_suit_price')
            ->where('day', '=', strtotime($use_date))
            ->and_where('suitid', '=', $suit_id)
            ->execute()
            ->current();
        if (!$price_arr) {
            throw new Exception('获取套餐报价失败');
        }

        // 如果有拼团价就执行拼团价格
        if (isset($together_price)) {
            $price_arr['adultprice']    = $together_price['adult_price'];
            $price_arr['childprice']    = $together_price['child_price'];
            $price_arr['oldprice']      = $together_price['old_price'];
            $price_arr['people4_price'] = $together_price['people4_price'];
            $price_arr['people5_price'] = $together_price['people5_price'];
            $price_arr['people6_price'] = $together_price['people6_price'];
        }
        $extend_data = array();
        if (isset($together_info)) {
            $extend_data['together_info'] = $together_info;
        }
        return array($info, $suit_info, $price_arr, $extend_data);
    }


    /**
     * 格式化价格
     * @param array $price_arr
     * @return array
     */
    public static function format_order_price($price_arr)
    {
        $price_key = array(
            'adultprice',
            'childprice',
            'oldprice',
            'people4_price',
            'people5_price',
            'people6_price',
            'roombalance'
        );

        foreach ($price_arr as $key => &$value) {
            if (in_array($key, $price_key)) {
                $value = Currency_Tool::price($value);
                $value = doubleval($value);
            }
        }
        return $price_arr;
    }

    /**
     * 获取订单信息
     * @param $request_data
     * @return array
     */
    public static function make_order_info($request_data, $info, $suit_info, $user_info)
    {
        // 联系人信息
        $linkman = trim(Common::remove_xss($request_data->linkman));
        $linktel = trim(Common::remove_xss($request_data->linktel));
        $linkemail = Common::remove_xss($request_data->linkemail);

        // 备注信息
        $remark = Common::remove_xss($request_data->remark);

        //积分抵现.
        $jifen_info = Model_Api_V2_Line::make_jifen_info($request_data, $info, $user_info);

        // 订单编号
        $ordersn = Product::get_ordersn('01');

        // 订单数据
        $data = array(
            'typeid' => self::$_typeid,
            'webid' => 0,
            'ordersn' => $ordersn,
            'productautoid' => $info['id'],
            'linkman' => $linkman,
            'linktel' => $linktel,
            'linkemail' => $linkemail,
            'remark' => $remark,
            'needjifen' => $jifen_info['need_jifen'],
            'usejifen' => $jifen_info['use_jifen'],
            'jifentprice' => $jifen_info['jifen_price'],
            'jifencomment' => $jifen_info['jifen_comment'],
            'memberid' => $user_info['mid'],
            'suitid' => $suit_info['id'],
            'addtime' => time(),
            'roombalance_paytype' => 1,   // 单房差默认线上支付
            'litpic' => $info['litpic'],
            'productaid' => $info['aid'],
            'productname' => $info['title'],
            'departdate' => $info['departdate'],
            'jifenbook' => $info['jifenbook_id'],
            'need_confirm' => $suit_info['need_confirm'],
            'suit_name' => $suit_info['suitname'],
            'refund_restriction' => $suit_info['refund_restriction'],
        );

        //成人数量
        $data['dingnum'] = $request_data->dingnum ? intval($request_data->dingnum) : 0;
        //小孩数量
        $data['childnum'] = $request_data->childnum ? intval($request_data->childnum) : 0;
        //老人数量
        $data['oldnum'] = $request_data->oldnum ? intval($request_data->oldnum) : 0;
        //人群4
        $data['people4_num'] = $request_data->people4num ? intval($request_data->people4num) : 0;
        //人群5
        $data['people5_num'] = $request_data->people5num ? intval($request_data->people5num) : 0;
        //人群6
        $data['people6_num'] = $request_data->people6num ? intval($request_data->people6num) : 0;
        //单房差数量
        $data['roombalancenum'] = $request_data->roombalancenum ? intval($request_data->roombalancenum) : 0;
        //出发日期
        $data['usedate'] = $request_data->usedate;
        // 订单来源 1PC,2WAP,3小程序,4平台添加
        $data['source'] = isset($request_data->source) ? $request_data->source : 3;
        // 自动关闭订单时间
        $auto_close_time = $suit_info['auto_close_time'] ?: 0;
        if ($auto_close_time) {
            $data['auto_close_time'] = $auto_close_time + time();
        }
        // 待确认时限
        $auto_confirm_time = $suit_info['auto_confirm_time'] ?: 0;
        if ($auto_confirm_time) {
            $data['auto_confirm_time'] = $auto_confirm_time + time();
        }
        // 合同判断
        if ($info['contractid']) {
            $contract            = Model_Contract::get_contents($info['contractid'], 1);
            $data['contract_id'] = $contract ? $info['contractid'] : 0;
        }

        $seckill_id = intval($request_data->seckill_id);
        // 保存价格相关信息
        if ($seckill_id > 0 && St_Functions::is_normal_app_install('seckill')) {
            $data['paytype'] = 1;
            $data['pay_way'] = 1;
            $data['dingjin'] = 0;
        } else {
            $data['paytype'] = $suit_info['paytype'];
            $data['pay_way'] = $suit_info['pay_way'];
            $data['dingjin'] = doubleval($suit_info['dingjin']);
        }

        return $data;
    }

    public static function make_jifen_info($request_data, $hotel, $user_info)
    {
        $need_jifen  = $request_data->needjifen ? intval($request_data->needjifen) : 0;
        $jifen_price = 0;
        $use_jifen   = 0;
        if ($need_jifen) {
            $jifen_price = Model_Jifen_Price::calculate_jifentprice($hotel['jifentprice_id'], 1, $need_jifen, $user_info);
            $use_jifen   = empty($jifen_price) ? 0 : 1;
            $need_jifen  = empty($jifen_price) ? 0 : $need_jifen;
        }

        //积分评论
        $jifen_comment_info = Model_Jifen::get_used_jifencomment(1);
        $jifen_comment      = empty($jifen_comment_info) ? 0 : $jifen_comment_info['value'];

        return compact('need_jifen', 'use_jifen', 'jifen_comment', 'jifen_price');
    }

    /**
     * 生成发票信息
     * @param $order_id
     * @param $request_data
     * @return void
     */
    public static function add_order_bill_info($order_id, $request_data)
    {
        // 订单发票信息
        $receipt = $request_data->receiptInfo;

        $bill_info = '';
        $use_bill  = false;
        if ($receipt) {
            $receiptInfo = json_decode($receipt, true);
            if ($receiptInfo) {
                //发票
                $invoice_type = $receiptInfo['type'];
                $bill_info    = array(
                    'title' => $receiptInfo['title'],
                    'content' => $receiptInfo['content'],
                    'type' => $invoice_type,
                    'taxpayer_number' => $invoice_type != 0 ? $receiptInfo['taxpayer_number'] : '',
                    'taxpayer_address' => $invoice_type == 2 ? $receiptInfo['taxpayer_address'] : '',
                    'taxpayer_phone' => $invoice_type == 2 ? $receiptInfo['taxpayer_phone'] : '',
                    'bank_branch' => $invoice_type == 2 ? $receiptInfo['bank_branch'] : '',
                    'bank_account' => $invoice_type == 2 ? $receiptInfo['bank_account'] : ''
                );
                // 发票地址
                if (isset($receiptInfo['address']) && !empty($receiptInfo['address'])) {
                    $receiptAddress        = $receiptInfo['address'];
                    $bill_info['mobile']   = $receiptAddress['phone'];
                    $bill_info['receiver'] = $receiptAddress['receiver'];
                    $bill_info['postcode'] = $receiptAddress['postcode'];
                    $bill_info['province'] = $receiptAddress['province'];
                    $bill_info['city']     = $receiptAddress['city'];
                    $bill_info['address']  = $receiptAddress['address'];
                }
                $use_bill = true;
            }
        }

        if ($use_bill) {
            Model_Member_Order_Bill::add_bill_info($order_id, $bill_info);
        }
    }


    /**
     * 添加订单保险信息
     * @param $order
     * @param $tourist
     * @param $request_data
     * @return void
     */
    public static function add_order_insurance($order, $tourist, $request_data)
    {
        // 保险信息
        $base_id = $request_data->baseid;
        $plan_id = $request_data->planid;
        if ($base_id && $plan_id) {
            // 添加保险
            $base_id_arr    = explode(',', $base_id);
            $plan_id_arr    = explode(',', $plan_id);
            $people_num_arr = array(
                $order['dingnum'],
                $order['childnum'],
                $order['oldnum'],
                $order['people4_num'],
                $order['people5_num'],
                $order['people6_num'],
            );
            $total_num      = St_Math::add($people_num_arr, 0);
            $ins_num        = count($base_id_arr);
            for ($i = 0; $i < $ins_num; $i++) {
                if (empty($baseid_arr[$i])) {
                    continue;
                }
                $params = array(
                    '$orderSn' => $order['ordersn'],
                    'dingnum' => $total_num,
                    'baseid' => $base_id_arr[$i],
                    'planid' => $plan_id_arr[$i],
                    'tours' => $tourist,
                    'memberid' => $order['memberid'],
                    'usedate' => $order['usedate']
                );
                Model_Insurance_Base::add_product_order($params);
            }
        }
    }

    /**
     * 添加订单游客信息
     * @param $tourists
     * @param $order_id
     * @return void
     * @throws Kohana_Exception
     */
    public static function add_order_tourists($tourists, $order_id)
    {
        if ($tourists && is_array($tourists)) {
            foreach ($tourists as $v) {
                $arr = array(
                    'orderid' => $order_id,
                    'tourername' => $v['linkman'],
                    'sex' => $v['sex'],
                    'mobile' => $v['mobile'],
                    'cardtype' => $v['cardtype'],
                    'cardnumber' => $v['idcard'],
                    'en_first_name' => $v['en_first_name'],
                    'en_last_name' => $v['en_last_name'],
                    'nationality' => $v['nationality'],
                    'cardnumber_expire_date' => $v['cardnumber_expire_date'],
                    'birth' => $v['birth'],
                );
                DB::insert('member_order_tourer', array_keys($arr))->values(array_values($arr))->execute();
            }
        }
    }

    /**
     * 添加秒杀订单
     * @param $seckill_id
     * @param $price_arr
     * @param $order
     * @return void
     */
    public static function add_order_seckill($request_data, $price_arr, $order)
    {
        $seckill_id = $request_data->seckill_id ? intval($request_data->seckill_id) : 0;
        if ($seckill_id > 0 && St_Functions::is_normal_app_install('seckill')) {
            $seckill = DB::select()
                ->from('seckill')
                ->where('id', '=', $seckill_id)
                ->execute()
                ->current();
            if ($seckill) {
                $seckill['suit_original_adult_price']   = $price_arr['adultprice'];
                $seckill['suit_original_child_price']   = $price_arr['childprice'];
                $seckill['suit_original_old_price']     = $price_arr['oldprice'];
                $seckill['suit_original_people4_price'] = $price_arr['people4_price'];
                $seckill['suit_original_people5_price'] = $price_arr['people5_price'];
                $seckill['suit_original_people6_price'] = $price_arr['people6_price'];
                Model_Seckill::add_seckill_order($order, $seckill);
            }
        }
    }

    /**
     * 获取线路产品出发城市列表
     * @return array
     */
    public static function get_start_citys(){
        return DB::select(DB::expr('sline_startplace.id,sline_startplace.pid,sline_startplace.cityname as name,sline_startplace.displayorder,sline_startplace.isopen'))
            ->from('line_startplace')
            ->join('startplace', 'right')
            ->on('startplace.id', '=', DB::expr('sline_line_startplace.`startplace_id`'))
            ->where('line_startplace.isopen', '=',1)
            ->order_by(DB::expr('ifnull(sline_line_startplace.displayorder,9999)'), 'asc')
            ->execute()
            ->as_array();
    }

    /**
     * 获取两级属性
     * @return array
     */
    public static function get_attributes()
    {
        $data = self::get_attribute();
        foreach ($data as &$item) {

            $item['child'] = self::get_attribute($item['id']);
        }

        return $data;
    }

    /**
     * 按pid获取属性
     * @param $pid
     * @return array
     */
    public static function get_attribute($pid = 0)
    {
        return DB::select('id', array('attrname', 'name'))
            ->from('line_attr')
            ->where('pid', '=', $pid)
            ->and_where('isopen', '=', 1)
            ->order_by(DB::expr('ifnull(displayorder,9999)'), 'asc')
            ->execute()
            ->as_array();
    }

    /**
     * 获取天数
     * @return array
     */
    public static function get_days()
    {
        $data = DB::select()->from('line_day')->execute()->as_array();
        $auto_index = 1;
        foreach ($data as &$r) {
            $number = substr($r['word'], 0, 2);
            $arr    = array("零", "一", "二", "三", "四", "五", "六", "七", "八", "九");
            if (strlen($number) == 1) {
                $days = $arr[$number];
            } else {
                if ($number == 10) {
                    $days = "十";
                } else {
                    if ($number < 20) {
                        $days = "十";
                    } else {
                        $days = $arr[substr($number, 0, 1)] . "十";
                    }
                    if (substr($number, 1, 1) != "0") {
                        $days .= $arr[substr($number, 1, 1)];
                    }
                }
            }
            if ($auto_index == count($data['filter']['day']['child'])) {
                $r['name'] = $days . "日游以上";
            } else {
                $r['name'] = $days . "日游";
            }
            $auto_index++;
        }
        return $data;
    }

    /**
     * 获取价格
     * @return array
     */
    public static function get_prices()
    {
        $data = DB::select()
            ->from('line_pricelist')
            ->where('lowerprice', '>=', 0)
            ->order_by('lowerprice', 'asc')
            ->execute()
            ->as_array();
        foreach ($data as &$row) {
            if ($row['lowerprice'] == 0 && $row['highprice'] != 0) {
                $row['name'] = Currency_Tool::symbol() . $row['highprice'] . '以下';
            } else if ($row['highprice'] == '' || $row['highprice'] == 0) {
                $row['name'] = Currency_Tool::symbol() . $row['lowerprice'] . '以上';
            } else if ($row['lowerprice'] != '' && $row['highprice'] != '') {
                $row['name'] = Currency_Tool::symbol() . $row['lowerprice'] . '-' . Currency_Tool::symbol() . $row['highprice'];
            }
        }
        return $data;
    }

}